#include <python2.5/Python.h>
#include <string>
#include <iostream>
#include "./include/dicttrie.h"
#include "./include/pinyinime.h"


using namespace std;
using namespace ime_pinyin;

static char Hanzi_buf[100];

int convertUTF16UTF8(char* utf16, int& size16, char* utf8, int& size8)
{
int i=0, count=0;
char tmp1/*, tmp2*/;

unsigned short int integer;
for(i=0;i<size16 ; i++)
{
integer = *(unsigned short int*)&utf16[i];

if( integer<0x80)
{
utf8[count] = utf16[i] & 0x7f;
count++;
}
else if( integer>=0x80 && integer<0x07ff)
{
tmp1 = integer>>6;
utf8[count] = 0xC0 | (0x1F & integer>>6);
utf8[count+1] = 0x80 | (0x3F & integer);
count+=2;
}
else if( integer>=0x0800 )
{
tmp1 = integer>>12;
utf8[count] = 0xE0 | (0x0F & integer>>12);
utf8[count+1] = 0x80 | ((0x0FC0 & integer)>>6);
utf8[count+2] = 0x80 | (0x003F & integer);

count += 3;
}
else
{
printf("error\n");
}
}


size16 = i;
size8 = count;
return count;
}
///////////////////////////////////


int init()
{
	const char * sys_dict = "./dict/dict_pinyin.dat";
	const char * usr_dict= "./dict/usr_dict.dat";
	bool success = false;

	success = im_open_decoder( sys_dict, usr_dict );
	if( true==success )
	{
		cout<<"init successfully\n";
		return 1;
	}
	else
	{
		cout<<"init unsuccessfully\n";
		return 0;
	}

	return 0;
}

int search( const string pinyin )
{
	cout<<"search : "<<pinyin<<endl;
	int totalnum = im_search( pinyin.c_str(), pinyin.length() );
	
	if( totalnum<=0 )
		totalnum = 0;

	return totalnum;
}

char* get_candidate( int index )
{
	if( 0!=index )
		index = 0;
	
	memset( Hanzi_buf, 0, 100 );
	if( im_get_candidate(0, (char16*)Hanzi_buf, 100) )
	{	
		int utf16_length = utf16_strlen((char16*)Hanzi_buf);
		string strout = "";
		char tmp[100];
		int tmp_length = 100;
		memset( tmp, 0, 100 );
		for( int i=0; i<utf16_length; ++i )
		{
			int j = 1;
			convertUTF16UTF8( (&Hanzi_buf[i]), j, tmp,  tmp_length );	
			string str(tmp);
			strout += str;
		}
		cout<<"Chinese = "<<strout<<endl;
		memset( Hanzi_buf, 0, 100 );
		strcpy( Hanzi_buf, strout.c_str() );

		return Hanzi_buf;
	}
	else
		return NULL;
}



static PyObject* wrap_init( PyObject* self, PyObject* args )
{
	int ret = init();
	return Py_BuildValue( "i", ret );
}

static PyObject* wrap_search( PyObject* self, PyObject* args )
{
	const char* command;
	if( !PyArg_ParseTuple(args, "s", &command) )
		return NULL;
	int ret = search( command );

	return Py_BuildValue( "i", ret );
}

static PyObject* wrap_candidate( PyObject* self, PyObject* args )
{
	int index;
	if( !PyArg_ParseTuple(args, "i", &index) )
		return NULL;

	char* ret = get_candidate(index);
	return Py_BuildValue( "s", ret );
}


static PyMethodDef Methods[] = 
{
   {"init", wrap_init, METH_VARARGS, "init"},
   {"search", wrap_search, METH_VARARGS, "search"},
   {"candidate", wrap_candidate, METH_VARARGS, "candidate"},
   {NULL, NULL, 0, NULL} 
};

PyMODINIT_FUNC initgoogleime(void)
{
   PyObject *m = Py_InitModule("googleime", Methods);
   if (m == NULL) return;
}
